package com.jingdianjichi.subject.service.impl;

import com.alibaba.fastjson.JSON;
import com.jingdianjichi.subject.common.entity.PageResult;
import com.jingdianjichi.subject.common.enums.IsDeletedFlagEnum;
import com.jingdianjichi.subject.common.enums.SubjectLikedStatusEnum;
import com.jingdianjichi.subject.common.util.LoginUtil;
import com.jingdianjichi.subject.convert.SubjectLikedBOConverter;
import com.jingdianjichi.subject.entity.SubjectLikedBO;
import com.jingdianjichi.subject.infra.basic.entity.SubjectInfo;
import com.jingdianjichi.subject.infra.basic.entity.SubjectLiked;
import com.jingdianjichi.subject.infra.basic.service.SubjectInfoService;
import com.jingdianjichi.subject.infra.basic.service.SubjectLikedService;
import com.jingdianjichi.subject.redis.RedisUtil;
import com.jingdianjichi.subject.service.SubjectLikedDomainService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author 董代恒
 * @version 1.0
 */
@Service
@Slf4j
public class SubjectLikedDomainServiceImpl implements SubjectLikedDomainService {

    private static final String SUBJECT_LIKED_KEY = "subject.liked";
    private static final String SUBJECT_LIKED_COUNT_KEY = "subject.liked.count";
    private static final String SUBJECT_LIKED_DETAIL_KEY = "subject.liked.detail";
    @Resource
    private SubjectLikedService subjectLikedService;
    @Resource
    private SubjectInfoService subjectInfoService;
    @Resource
    private RedisUtil redisUtil;

    /**
     * 用户点赞
     *
     * @param subjectLikedBO
     */
    @Override
    public void add(SubjectLikedBO subjectLikedBO) {
        //获取点赞的题目id
        Long subjectId = subjectLikedBO.getSubjectId();
        //获取点赞用户Id
        String likeUserId = subjectLikedBO.getLikeUserId();
        //获取点赞状态
        Integer status = subjectLikedBO.getStatus();
        //将题目id和点赞用户id拼接成一个hashKey
        String hashKey = buildSubjectLikedKey(subjectId.toString(), likeUserId);
        //将点赞状态存入hashkey中
        redisUtil.putHash(SUBJECT_LIKED_KEY, hashKey, status);

        String detailKey = SUBJECT_LIKED_DETAIL_KEY + "." + subjectId + "." + likeUserId;

        //平均一个countkey这个key保存题目被用户点赞的数量
        String countKey = SUBJECT_LIKED_COUNT_KEY + "." + subjectId;

        //根据点赞的状态来判断怎么存
        //如果状态的点赞就加1
        if (SubjectLikedStatusEnum.LIKED.getCode() == status) {
            redisUtil.increment(countKey, 1);

            //TODO:有这个key就表示点赞成功了?这个逻辑目前不理解啊?
            redisUtil.set(detailKey, "1");
        } else {
            Integer count = redisUtil.getInt(countKey);
            if (Objects.isNull(count) || count <= 0) {
                return;
            }
            //如果状态的取消点赞，那么就-1
            redisUtil.increment(countKey, -1);
            //TODO:如果取消点赞就把这个key删除了?这个逻辑目前不理解啊?
            redisUtil.del(detailKey);
        }


    }

    private String buildSubjectLikedKey(String subjectId, String userId) {
        return subjectId + ":" + userId;
    }

    @Override
    public Boolean isLiked(String subjectId, String userId) {
        String detailKey = SUBJECT_LIKED_DETAIL_KEY + "." + subjectId + "." + userId;
        return redisUtil.exist(detailKey);
    }

    @Override
    public Integer getLikedCount(String subjectId) {
        String countKey = SUBJECT_LIKED_COUNT_KEY + "." + subjectId;
        Integer count = redisUtil.getInt(countKey);
        if (Objects.isNull(count) || count <= 0) {
            return 0;
        }
        return redisUtil.getInt(countKey);
    }

    @Override
    public Boolean update(SubjectLikedBO subjectLikedBO) {
        SubjectLiked subjectLiked = SubjectLikedBOConverter.INSTANCE.convertBOToEntity(subjectLikedBO);
        return subjectLikedService.update(subjectLiked) > 0;
    }

    @Override
    public Boolean delete(SubjectLikedBO subjectLikedBO) {
        SubjectLiked subjectLiked = new SubjectLiked();
        subjectLiked.setId(subjectLikedBO.getId());
        subjectLiked.setIsDeleted(IsDeletedFlagEnum.DELETED.getCode());
        return subjectLikedService.update(subjectLiked) > 0;
    }

    /**
     * 同步redis点赞数据到数据库,数据持久化
     */
    @Override
    public void syncLiked() {
        Map<Object, Object> subjectLikedMap = redisUtil.getHashAndDelete(SUBJECT_LIKED_KEY);
        if (log.isInfoEnabled()) {
            log.info("syncLiked.subjectLikedMap:{}", JSON.toJSONString(subjectLikedMap));
        }
        if (MapUtils.isEmpty(subjectLikedMap)) {
            return;
        }

        //将redis里面缓存的点赞数据批量同步到数据库
        List<SubjectLiked> subjectLikedList = new LinkedList<>();

        subjectLikedMap.forEach((key, val) -> {
            SubjectLiked subjectLiked = new SubjectLiked();
            //key:101.oAxu-6KMlBLkfA13347csFcoga4w --->这个hash里面的key，不是redis的key，redis的key是subject.liked
            String[] keyArr = key.toString().split(":");
            String subjectId = keyArr[0];
            String likedUser = keyArr[1];
            //设置点赞题目id
            subjectLiked.setSubjectId(Long.valueOf(subjectId));
            //设置点赞人id
            subjectLiked.setLikeUserId(likedUser);
            //设置点赞状态 1:点赞  2:取消点赞
            subjectLiked.setStatus(Integer.valueOf(val.toString()));
            //设置点赞行记录默认添加时候是未删除
            subjectLiked.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());

            //将组装好的subjectLiked点赞实体类放到集合中
            subjectLikedList.add(subjectLiked);
        });
        //将点赞实体类集合批量添加到数据库中
        subjectLikedService.batchInsertOrUpdate(subjectLikedList);
    }


    /**
     * 查询点赞列表
     *
     * @param subjectLikedBO
     * @return
     */
    @Override
    public PageResult<SubjectLikedBO> getSubjectLikedPage(SubjectLikedBO subjectLikedBO) {
        PageResult<SubjectLikedBO> pageResult = new PageResult<>();
        pageResult.setPageNo(subjectLikedBO.getPageNo());
        pageResult.setPageSize(subjectLikedBO.getPageSize());
        int start = (subjectLikedBO.getPageNo() - 1) * subjectLikedBO.getPageSize();
        SubjectLiked subjectLiked = SubjectLikedBOConverter.INSTANCE.convertBOToEntity(subjectLikedBO);
        subjectLiked.setLikeUserId(LoginUtil.getLoginId());
        int count = subjectLikedService.countByCondition(subjectLiked);
        if (count == 0) {
            return pageResult;
        }
        List<SubjectLiked> subjectLikedList = subjectLikedService.queryPage(subjectLiked, start,
                subjectLikedBO.getPageSize());
        List<SubjectLikedBO> subjectInfoBOS = SubjectLikedBOConverter.INSTANCE.convertListInfoToBO(subjectLikedList);
        subjectInfoBOS.forEach(info -> {
            SubjectInfo subjectInfo = subjectInfoService.queryById(info.getSubjectId());
            info.setSubjectName(subjectInfo.getSubjectName());
        });
        pageResult.setRecords(subjectInfoBOS);
        pageResult.setTotal(count);
        return pageResult;
    }




}
